package com.qq.BFMRSE.requestModule;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.qq.BFMRSE.encrypt.desEncrypt;
import com.qq.BFMRSE.util.BFConstants;

public class decFileModule {
	private desEncrypt dEn;
	public decFileModule(desEncrypt dEn){
		this.dEn=dEn;
	}
	public desEncrypt getDEn(){
		return dEn;
	}
	public void setDEn(desEncrypt dEn){
		this.dEn=dEn;
	}
	public void decFiles(String enFilePath,String decFilePath){
		if(enFilePath.endsWith(BFConstants.TXTFILEEND)){
			//如果只是一个加密的txt文件
			String fileName=enFilePath.substring(enFilePath.lastIndexOf(File.separator)+1);
			decFilePath=decFilePath+File.separator+fileName;
			try {
				dEn.descrypt(new File(enFilePath), decFilePath);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(enFilePath.endsWith(BFConstants.ZIPFILEEND)){
			//如果解密的是压缩的zip文件
			try {
				ZipInputStream zin=new ZipInputStream(new FileInputStream(new File(enFilePath)));
				BufferedInputStream bin=new BufferedInputStream(zin);
				File fout=null;
				ZipEntry entry;
				File tmpFile=new File(BFConstants.ZIPTMP);
				if(!tmpFile.exists()||!tmpFile.isDirectory()){
					tmpFile.mkdir();
				}
				while((entry=zin.getNextEntry())!=null&&!entry.isDirectory()){
					String fileName=entry.getName();
					fout=new File(tmpFile, entry.getName());
					BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(fout));
					byte []buffer=new byte[1024];
					int len=0;
					while((len=bin.read(buffer))>0){
						bos.write(buffer, 0, len);
					}
					bos.close();
					String decFileName=decFilePath+File.separator+fileName;
					dEn.descrypt(new File(tmpFile, fileName), decFileName);
				}
				bin.close();
				zin.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				File tmpFile=new File(BFConstants.ZIPTMP);
				if(tmpFile.exists()&&tmpFile.isDirectory()){
					String []files=tmpFile.list();
					for(int i=0;i<files.length;i++){
						System.out.println(files[i]);
						File deleteFile=new File(tmpFile,files[i]);
						deleteFile.delete();
					}
				}
				tmpFile.delete();
			}
			
			
		}
	}
	

}
